/**
 * 用户状态指示组件
 * 显示当前用户登录状态和身份信息
 */

import React, { useState } from 'react';
import { Tag, Avatar, Space, Modal, Form, Input, message, notification, Button } from 'antd';
import { 
  UserOutlined, 
  SettingOutlined,
  BellOutlined,
  HeartOutlined,
  LogoutOutlined,
  EditOutlined,
  MailOutlined,
  LinkOutlined,
  CheckCircleOutlined
} from '@ant-design/icons';
import { useUserIdentity, useUserId } from '@/hooks';
import UserIdentityService from '@/services/UserIdentity';
import { updateAnonymousUserInfo } from '@/services/AnonymousUser/api';
import { history } from '@umijs/max';
import styles from './index.less';

interface UserStatusProps {
  showAvatar?: boolean;
  showUsername?: boolean;
  showTip?: boolean;
}

const UserStatus: React.FC<UserStatusProps> = ({ 
  showAvatar = true, 
  showUsername = true
}) => {
  const identity = useUserIdentity();
  const userId = useUserId();
  const [dropdownVisible, setDropdownVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [api, contextHolder] = notification.useNotification();

  const handleClick = () => {
    if (!identity.isLoggedIn) {
      history.push('/login');
    }
  };

  const handleLogout = () => {
    UserIdentityService.clearUserInfo();
    setDropdownVisible(false);
    history.push('/home');
    window.location.reload(); // 刷新页面以重新获取匿名ID
  };

  // 打开编辑模态框
  const handleEditInfo = () => {
    const localName = localStorage.getItem('anonymousUserName') || '';
    const localEmail = localStorage.getItem('anonymousUserEmail') || '';
    const localLink = localStorage.getItem('anonymousUserLink') || '';
    
    form.setFieldsValue({
      name: localName,
      email: localEmail,
      link: localLink,
    });
    
    setEditModalVisible(true);
    setDropdownVisible(false);
  };

  // 提交修改
  const handleSubmitEdit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      const result = await updateAnonymousUserInfo({
        userId: userId!,
        name: values.name,
        email: values.email,
        link: values.link,
      });

      if (result.data.success) {
        // 更新localStorage
        localStorage.setItem('anonymousUserName', values.name);
        localStorage.setItem('anonymousUserEmail', values.email);
        if (values.link) {
          localStorage.setItem('anonymousUserLink', values.link);
        } else {
          localStorage.removeItem('anonymousUserLink');
        }

        // 获取当前时间段的问候语
        const getGreeting = () => {
          const hour = new Date().getHours();
          if (hour < 12) return '早上好';
          if (hour < 18) return '中午好';
          return '晚上好';
        };

        // 显示美化的通知
        const key = `open${Date.now()}`;
        const btn = (
          <Button 
            type="primary" 
            size="small" 
            onClick={() => api.destroy(key)}
            style={{
              background: '#0891b2',
              borderRadius: '6px',
              fontWeight: 500
            }}
          >
            确认
          </Button>
        );

        api.success({
          message: (
            <div style={{ fontWeight: 600, color: '#262626', fontSize: '16px' }}>
              🎉 {getGreeting()}，{values.name}
            </div>
          ),
          description: (
            <div style={{ color: '#595959', lineHeight: '1.8' }}>
              <div style={{ marginBottom: '8px' }}>
                <span style={{ fontWeight: 600, color: '#262626' }}>您的邮箱为：</span>
                <span style={{ color: '#595959' }}>{values.email}</span>
              </div>
              {values.link && values.link.trim() && (
                <div style={{ marginBottom: '8px' }}>
                  <span style={{ fontWeight: 600, color: '#262626' }}>个人网址为：</span>
                  <span style={{ color: '#595959' }}>{values.link}</span>
                </div>
              )}
              <div style={{ 
                marginTop: '12px', 
                paddingTop: '12px', 
                borderTop: '1px solid #e5e7eb',
                fontSize: '13px',
                color: '#8c8c8c',
                fontWeight: 500
              }}>
                💡 后续可以在 
                <span style={{ fontWeight: 600, color: '#0891b2', margin: '0 4px' }}>游客模式</span> 
                按钮中修改喔
              </div>
            </div>
          ),
          btn,
          key,
          duration: 0,
          placement: 'topRight',
          style: {
            width: 400,
            background: '#ffffff',
            border: '1px solid #e5e7eb',
            boxShadow: '0 8px 24px rgba(0, 0, 0, 0.08), 0 2px 8px rgba(0, 0, 0, 0.04)',
            borderRadius: '16px',
          },
          icon: <CheckCircleOutlined style={{ color: '#0891b2', fontSize: '28px' }} />,
        });

        setEditModalVisible(false);
      } else {
        message.error(result.data.message || '更新失败，请重试');
      }
    } catch (error) {
      if (error instanceof Error && 'errorFields' in error) {
        message.warning('请填写必填信息');
      } else {
        message.error('更新失败，请重试');
      }
    } finally {
      setLoading(false);
    }
  };

  if (identity.isLoggedIn) {
    return (
      <>
        {contextHolder}
        <div 
          className={styles.userStatusDropdown}
          onMouseEnter={() => setDropdownVisible(true)}
          onMouseLeave={() => setDropdownVisible(false)}
        >
        <Space className={styles.userStatus}>
          {showAvatar && (
            <Avatar 
              src={identity.avatar} 
              icon={<UserOutlined />}
              size="small"
            />
          )}
          {showUsername && (
            <span className={styles.username}>{identity.username || '用户'}</span>
          )}
          <Tag color="success">已登录</Tag>
        </Space>

        {/* 下拉菜单 */}
        <div className={`${styles.dropdown} ${dropdownVisible ? styles.visible : ''}`}>
          <div className={styles.menuItem} onClick={() => console.log('个人中心')}>
            <SettingOutlined className={styles.menuIcon} />
            <span>个人中心</span>
          </div>
          <div className={styles.menuItem} onClick={() => console.log('消息通知')}>
            <BellOutlined className={styles.menuIcon} />
            <span>消息通知</span>
          </div>
          <div className={styles.menuItem} onClick={() => console.log('我的收藏')}>
            <HeartOutlined className={styles.menuIcon} />
            <span>我的收藏</span>
          </div>
          <div className={styles.divider}></div>
          <div className={`${styles.menuItem} ${styles.logoutItem}`} onClick={handleLogout}>
            <LogoutOutlined className={styles.menuIcon} />
            <span>退出登录</span>
          </div>
        </div>
        </div>
      </>
    );
  }

  // 未登录时，显示游客模式按钮和编辑下拉菜单
  return (
    <>
      {contextHolder}
      <div 
        className={styles.guestStatusDropdown}
        onMouseEnter={() => setDropdownVisible(true)}
        onMouseLeave={() => setDropdownVisible(false)}
      >
        <button type="button" className={styles.guestButton} onClick={handleClick}>
          <div className={styles.slideBlock}>
            <svg
              width="20px"
              height="20px"
              viewBox="0 0 1024 1024"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                fill="currentColor"
                d="M224 480h640a32 32 0 1 1 0 64H224a32 32 0 0 1 0-64z"
              ></path>
              <path
                fill="currentColor"
                d="m237.248 512 265.408 265.344a32 32 0 0 1-45.312 45.312l-288-288a32 32 0 0 1 0-45.312l288-288a32 32 0 1 1 45.312 45.312L237.248 512z"
              ></path>
            </svg>
          </div>
          <p className={styles.buttonText}>游客模式</p>
          <p className={styles.buttonTextHover}>登录</p>
        </button>

        {/* 游客模式下拉菜单 */}
        <div className={`${styles.dropdown} ${dropdownVisible ? styles.visible : ''}`}>
          <div className={styles.menuItem} onClick={handleEditInfo}>
            <EditOutlined className={styles.menuIcon} />
            <span>修改信息</span>
          </div>
        </div>
      </div>

      {/* 编辑信息模态框 */}
      <Modal
        title={
          <span style={{ color: '#0891b2', fontWeight: 600 }}>
            ✏️ 编辑个人信息
          </span>
        }
        open={editModalVisible}
        onOk={handleSubmitEdit}
        onCancel={() => setEditModalVisible(false)}
        confirmLoading={loading}
        okText="保存"
        cancelText="取消"
        width={500}
        styles={{
          header: {
            background: 'linear-gradient(135deg, #ecfeff 0%, #cffafe 100%)',
            borderBottom: '1px solid #67e8f9',
          },
        }}
      >
        <Form
          form={form}
          layout="vertical"
          style={{ marginTop: 20 }}
        >
          <Form.Item
            name="name"
            label="昵称"
            rules={[{ required: true, message: '请输入昵称' }]}
          >
            <Input
              prefix={<UserOutlined style={{ color: '#06b6d4' }} />}
              placeholder="请输入昵称"
              maxLength={20}
            />
          </Form.Item>
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' },
            ]}
          >
            <Input
              prefix={<MailOutlined style={{ color: '#06b6d4' }} />}
              placeholder="请输入邮箱"
              maxLength={50}
            />
          </Form.Item>
          <Form.Item
            name="link"
            label="个人网址（选填）"
            rules={[{ type: 'url', message: '请输入有效的网址' }]}
          >
            <Input
              prefix={<LinkOutlined style={{ color: '#06b6d4' }} />}
              placeholder="请输入个人网址"
              maxLength={100}
            />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default UserStatus;













